// import Notification from '../components/notification'
// import { auth } from './auth'
const sessionStorage = window.sessionStorage

export const interceptor = function (Vue) {
  Vue.http.interceptors.push((request, next) => {
    let tokenVal = sessionStorage.getItem('token')
    if (tokenVal) {
      request.headers['token'] = tokenVal
      // req.beforeSend = function() {
      //   req.headers['token'] = tokenVal
      // }
    }

    next((response) => {
      let status = response.status
      let data = response.data
      try {
        if (typeof data === 'string') {
          data = JSON.parse(data)
        }
      } catch (e) {

      }
      // let isError = false
      // let duration = 0
      // let self = this
      let options = {
        message: '',
        onClose: () => {
          // debugger
        }
      }
      // debugger
      if (status === 401) {
        // router.push('/login')
        window.location.href = '/login'
      } else if (status === 500) {
        // isError = true
        Message.close('loading')
        // options.message = response.statusText
        // options.description = response.data
        // options.duration = 0
        // options.showClose = true;
        // Message.error(options)

        Notice.error({
          title: response.statusText,
          desc: response.data,
          duration: 0
        })

        // setTimeout(()=>{
          // window.location.href = '/login'
        // }, 2000)
      } else if (status === 200) {
        // custom error
        if (response.data['<isError>']) {
          // isError = true
          options.title = ' '
          options.desc = `${data.message} `
          Message.error(options)
        } else if (data.data && data.data['ecode'] === '401') { // timeout
          // isError = true
          options.desc = data.data['msg'] || 'Timeout...'
          options.duration = 3
          options.key = 'timeout-error'
          // setTimeout(()=>{
          window.location.href = '/login'
          // }, 2000)
          Message.error(options)
        }
      }
      // isError && Message.error(options)
      // return response
    })
  })
}
